//
//  SWEffectViewController.swift
//  ChildStory
//
//  Created by linhan on 16/8/29.
//  Copyright © 2016年 Aiya. All rights reserved.
//

import Foundation

class SWEffectViewController: SWBaseViewController,UICollectionViewDataSource,UICollectionViewDelegate,SWFilterDelegate
{
    weak var image:UIImage?
    weak var delegate:SWImageProcessViewControllerDelegate?
    
    private var _change:Bool = false
    private var _origin:UIImage
    private var _result:UIImage?
    private var _thumb:UIImage?
    
    //缓存磨皮过的图片以提高处理速度
    private var _skinSmoothImage:UIImage?
    
    private var _filters:[SWBaseFilter] = []
    private var _filter:SWBaseFilter?
    
    private var _imageView = UIImageView()
    
    private let CellIdentifier:String = "InstaFiltersCollectionCell"
    private var _collectionView:UICollectionView?
    
    init(origin:UIImage)
    {
        _origin = origin
        
        //将图片缩小以加快滤镜的显示
        let originSize:CGSize = origin.originSize
        let containerSize:CGSize = UIScreen.main.bounds.size.multiply(UIScreen.main.scale)
        var scale:CGFloat = ViewUtil.getAdaptiveScale(originSize.width, targetH: originSize.height, containerW: containerSize.width, containerH: containerSize.height)
        var size:CGSize = originSize
        if scale < 1
        {
            size = CGSizeMake(originSize.width * scale, originSize.height * scale)
        }
        //适中图
        _result = origin.imageScaled(toConstrainSize: size)?.retinaImage ?? origin
        print("_result:", _result?.size, _result?.scale)
        //缩略图
        scale = ViewUtil.getAdaptiveScale(originSize.width, targetH: originSize.height, containerW: 80, containerH: 80)
        size = CGSizeMake(originSize.width * scale, originSize.height * scale)
        _thumb = origin.imageScaled(toConstrainSize: size)?.retinaImage ?? origin
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //隐藏导航栏
    override var prefersNavigationBarHidden: Bool{
        return true
    }
    
    //隐藏状态栏
    override var prefersStatusBarHidden:Bool {
        return true
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setup()
    }
    
    deinit
    {
        print("DEINIT SWEffectViewController")
    }
    
    private func setup()
    {
        view.backgroundColor = UIColor(hex: 0x232222)
        automaticallyAdjustsScrollViewInsets = false
        
        let BottomToolViewHeight:CGFloat = 62
        let TopToolViewHeight:CGFloat = 62
        
        let closeBtn:UIButton = UIButton(type: .custom)
        closeBtn.setImage(UIImage(named: "editor_icon_cancel"), for: .normal)
        closeBtn.sizeToTouchEasy()
        closeBtn.center = CGPointMake(22, 22)
        closeBtn.addTarget(self, action: #selector(cancelBtnTapped), for: .touchUpInside)
        view.addSubview(closeBtn)
        
        let saveBtn:UIButton = UIButton(type: .custom)
        saveBtn.setImage(UIImage(named: "editor_icon_ok"), for: .normal)
        saveBtn.sizeToTouchEasy()
        saveBtn.center = CGPointMake(view.width - 22, 22)
        saveBtn.addTarget(self, action: #selector(confirmBtnTapped), for: .touchUpInside)
        view.addSubview(saveBtn)
        
        _filters.append(SWNormalWhiteFilter())
        _filters.append(SWDeepWhiteFilter())
        _filters.append(SWMengHuanFilter())
        _filters.append(SWPinkFilter())
        _filters.append(SWRouHeFilter())
        _filters.append(SWMemoryFilter())
        _filters.append(SWAmaroFilter())
        _filters.append(SWLomoFilter())
        
        for filter in _filters
        {
            filter.delegate = self
        }
        
        let imageViewHeight:CGFloat = view.height - TopToolViewHeight - BottomToolViewHeight
        _imageView.frame = CGRectMake(0, TopToolViewHeight, view.width, imageViewHeight)
        _imageView.image = _result
        _imageView.contentMode = .scaleAspectFit
        view.addSubview(_imageView)
        
        
        let ItemSize:CGSize = CGSizeMake(64, 88)
        let Grid:CGFloat = 3
        let layout:UICollectionViewFlowLayout = UICollectionViewFlowLayout()
        layout.itemSize = ItemSize
        //横向最小间隔
        layout.minimumLineSpacing = Grid
        layout.minimumInteritemSpacing = 0
        layout.sectionInset = UIEdgeInsetsMake(0, Grid, 0, Grid)
        layout.scrollDirection = .horizontal
        
        _collectionView = UICollectionView(frame: CGRectMake(0, view.height - ItemSize.height, view.width, ItemSize.height), collectionViewLayout: layout)
        _collectionView?.backgroundColor = UIColor.lightGray
        _collectionView?.allowsSelection = true
        _collectionView?.register(SWEffectCollectionCell.self, forCellWithReuseIdentifier: CellIdentifier)
        _collectionView?.dataSource = self
        _collectionView?.delegate = self
        view.addSubview(_collectionView!)
    }
    
    //执行滤镜
    private func execute(filter:SWBaseFilter)
    {
        if filter != _filter
        {
            _filter?.dispose()
            _filter = filter
            var info:[String:Any] = [:]
            if let skinSmoothImage = _skinSmoothImage{
                info[SWBaseFilter.SkinSmoothImageKey] = skinSmoothImage
            }
            
            if let image = _result
            {
                _filter?.execute(image: image, info:info)
                SVProgressHUD.show(withStatus: "处理中...")
            }
            
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
    {
        return _filters.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
    {
        let cell:SWEffectCollectionCell = collectionView.dequeueReusableCell(withReuseIdentifier:CellIdentifier, for: indexPath) as! SWEffectCollectionCell
        cell.thumb = _thumb
        cell.filter = _filters[indexPath.row]
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath)
    {
        _change = true
        if let filter = _filters.valueAt(indexPath.row)
        {
            execute(filter: filter)
        }
    }
    
    func filterProcessCompletion(_ filter:SWBaseFilter, image:UIImage, info:[String:Any]?)
    {
        if let skinSmoothImage = info?[SWBaseFilter.SkinSmoothImageKey] as? UIImage{
            _skinSmoothImage = skinSmoothImage
        }
        _result = image
        
        DispatchQueue.main.async {
            self._imageView.image = image
            SVProgressHUD.dismiss()
        }
        
    }
    
    func filterProcessFail(_ filter:SWBaseFilter, error:NSError)
    {
        print("filterProcessFail")
        SVProgressHUD.dismiss()
        //_collectionView?.deselectItemAtIndexPath(<#T##indexPath: IndexPath##IndexPath#>, animated: <#T##Bool#>)
    }
    
    @objc private func cancelBtnTapped()
    {
        dismiss(animated:false, completion: nil)
    }
    
    @objc private func confirmBtnTapped()
    {
        if let filter = _filter,_change
        {
            SVProgressHUD.show(withStatus: "处理中...")
            filter.execute(image: _origin, info: nil, successCallback: {[weak self] image in
                
                if let strongSelf = self{
                    strongSelf.delegate?.imageProcessViewController(controller: strongSelf, didFinishProcessImage: image, additionInfo: nil)
                }
                DispatchQueue.main.async {
                    SVProgressHUD.dismiss()
                }
                
                }, failCallback: { error in
                    DispatchQueue.main.async {
                        SVProgressHUD.dismiss()
                    }
            })
            
            
        }
        else
        {
            cancelBtnTapped()
        }
    }
    
}
